package gray.boolber.vk.adapter;

import gray.boolber.utils.AsyncQueue;
import gray.boolber.utils.AsyncUIQueue;
import gray.boolber.utils.LeaksManager;
import gray.boolber.vk.R;
import gray.boolber.vk.web.api.items.Attachment;
import gray.boolber.vk.web.api.items.News;
import gray.boolber.vk.web.api.items.Photo;
import gray.boolber.vk.web.api.manager.NewsFeedManager;
import gray.boolber.vk.web.api.utils.StorageManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

public class NewsFeedAdapter extends BaseAdapter{
    
    private ArrayList<News> items ;
    private Context context;
	private LayoutInflater inflater;
	private String rootFolder;
	private AsyncQueue asyncQueue;
	private WindowManager wm;
	private Display display;
	private AsyncUIQueue asyncUIQueue;
	private static final double BASE_ASPECTRATIO=0.5;
	public static class ViewHolder{
		public ImageView logo;
		public ImageView bm;
		public TextView title;
		public TextView text;
		public int position;
		public HorizontalScrollView galery;
		public LinearLayout gallery_root;
	}
    public NewsFeedAdapter(Context context){
        this.context=context;
        inflater = LayoutInflater.from(context);
        items=NewsFeedManager.INSTANCE.items;
        //String path=context.getCacheDir().getAbsolutePath()+"/cache/magazines/"+magazine.getFilename();
        asyncQueue=new AsyncQueue(9);
//        asyncUIQueue=new AsyncUIQueue(1);
    	rootFolder=StorageManager.getExternalStoragePath()+"/content/";
    	new File(rootFolder).mkdirs();
    	wm=(WindowManager) context.getSystemService(Activity.WINDOW_SERVICE);
	    display=wm.getDefaultDisplay();
    }

	@Override
	public int getCount() {
		return items.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}
	@Override
	public void notifyDataSetInvalidated() {
		Log.i("BOOLBER", "+called");
		super.notifyDataSetInvalidated();
	}
	@Override
	public void notifyDataSetChanged() {
		Log.i("BOOLBER", "+called");
		super.notifyDataSetChanged();
	}
	
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
//		long tn=System.nanoTime();
		long t=System.currentTimeMillis();
		if (convertView == null) {
   	       convertView =inflater.inflate(R.layout.newsfeed_item, null);
	    }
		ViewHolder vh=(ViewHolder)convertView.getTag();
		if(vh==null){
			Log.i("BOOLBER", "view holder");
			vh=new ViewHolder();
			vh.logo=((ImageView)convertView.findViewById(R.id.newsfeed_item_user_avatar));
			vh.bm=((ImageView)convertView.findViewById(R.id.newsfeed_item_logo));
			vh.text=((TextView)convertView.findViewById(R.id.newsfeed_item_text));
			vh.title=((TextView)convertView.findViewById(R.id.newsfeed_item_title));
			vh.galery=((HorizontalScrollView)convertView.findViewById(R.id.newsfeed_item_galery));
			vh.gallery_root=((LinearLayout)convertView.findViewById(R.id.newsfeed_item_galery_root));
			vh.position=position;
			convertView.setTag(vh);
		}
		vh.position=position;
		vh.bm.setImageResource(R.drawable.blank_im);
		vh.bm.setScaleType(ScaleType.FIT_XY);
		prepareViewConfiguration(position, vh);
		//Log.i("BOOLBER", "+"+position+ " vh.pos "+vh.position);
		//initSourcePhoto(vh, position);
		initNewsPhoto(vh, position);
		
//		vh.text.setText(Html.fromHtml(items.get(position).getText()));
//		vh.title.setText(NewsFeedManager.INSTANCE.getSourceTitle(items.get(position).getSourceId()));
		//printLeaksManager();
		//((TextView)convertView.findViewById(R.id.content_page_number)).setText("p."+(position+1));
		Log.i("BOOLBER", ""+(System.currentTimeMillis()-t));
//		Log.i("BOOLBER", ""+(System.nanoTime()-tn)/1000.0);
		return convertView;
	}
//	private void setAttachments(ViewHolder vh,int position){
//		String thumbFile="";
//		String thumb_url="";
//		double asp=1.0;
//		ImageView item_thumb=vh.bm;
//		ArrayList<Attachment> attachments=items.get(position).getAttachments();
//		if(attachments!=null&&attachments.get(0).getType()==Attachment.Type.photo){
//			if(attachments.size()==1){
//				Photo photo=((Photo)attachments.get(0).getaFile());
//				thumbFile=rootFolder+""+((Photo)attachments.get(0).getaFile()).pid+".png";
//				thumb_url=photo.getBestNewsFeed();
//				asp=Double.parseDouble(photo.height)/Double.parseDouble(photo.width);
//				if(asp>BASE_ASPECTRATIO) asp=BASE_ASPECTRATIO;
//				item_thumb.setMinimumHeight((int) (display.getWidth()*asp));
//			}else if(attachments.size()>1){
//				Photo photo=null;
//				for(int i=0;i<attachments.size();i++){
//					photo=((Photo)attachments.get(i).getaFile());
//					thumbFile=rootFolder+""+((Photo)attachments.get(i).getaFile()).pid+".png";
//					thumb_url=photo.getBestNewsFeed();
//					asp=Double.parseDouble(photo.height)/Double.parseDouble(photo.width);
//					if(asp>BASE_ASPECTRATIO) asp=BASE_ASPECTRATIO;
//					item_thumb.setMinimumHeight((int) (display.getWidth()*asp));
//					asyncQueue.execute(new ImageLoader(vh,thumb_url,thumbFile,position));
//				}
//				
//			}
//		}else if(item.getPhotos()!=null){
//			if(item.getPhotos().size()>1){
//				vh.bm.setVisibility(View.GONE);
//				vh.galery.setVisibility(View.VISIBLE);
//			}else{
//				vh.bm.setVisibility(View.VISIBLE);
//				vh.galery.setVisibility(View.GONE);
//			}
//		}
//	}
	private void initNewsPhoto(ViewHolder vh,int position){
		String thumbFile="";
		String thumb_url="";
		double asp=1.0;
		ImageView item_thumb=vh.bm;
		Attachment attachment=items.get(position).getAttachment();
		if(attachment!=null&&attachment.getType()==Attachment.Type.photo){
			Photo photo=((Photo)attachment.getaFile());
			thumbFile=rootFolder+""+((Photo)attachment.getaFile()).pid+".png";
			thumb_url=photo.getBestNewsFeed();
			asp=Double.parseDouble(photo.height)/Double.parseDouble(photo.width);
			if(asp>BASE_ASPECTRATIO) asp=BASE_ASPECTRATIO;
			//item_thumb.setMinimumHeight((int) (display.getWidth()*asp));
		}else if(attachment==null && items.get(position).getPhotos()!=null){
			Photo photo=items.get(position).getPhotos().get(0);
			thumbFile=rootFolder+""+items.get(position).getPhotos().get(0).pid+".png";
			thumb_url=items.get(position).getPhotos().get(0).getBestNewsFeed();
			asp=Double.parseDouble(photo.height)/Double.parseDouble(photo.width);
			if(asp>BASE_ASPECTRATIO) asp=BASE_ASPECTRATIO;
		//	item_thumb.setMinimumHeight((int) (display.getWidth()*asp));
		}else{
			//item_thumb.setMinimumHeight((int) (display.getWidth()*0.09));
		}
		item_thumb.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(((ImageView)v).getScaleType()==ScaleType.CENTER_CROP){
					((ImageView)v).setScaleType(ScaleType.CENTER_INSIDE);
				}else{
					((ImageView)v).setScaleType(ScaleType.CENTER_CROP);
				}
				
			}
		});
		item_thumb.setTag(position);
		
		if(thumb_url.length()>0 && thumbFile.length()>0){
			asyncQueue.execute(new ImageLoader(vh,thumb_url,thumbFile,position));
//			new AsyncImageLoader().execute(thumb_url,thumbFile,vh,position);
		}
	}
	private void prepareViewConfiguration(int pos,ViewHolder vh){
		News item=items.get(pos);
		if(item.getAttachments()!=null){
			if(item.getAttachments().size()>1){
				vh.bm.setVisibility(View.GONE);
				vh.galery.setVisibility(View.VISIBLE);
			}else{
				vh.bm.setVisibility(View.VISIBLE);
				vh.galery.setVisibility(View.GONE);
			}
		}else if(item.getPhotos()!=null){
			if(item.getPhotos().size()>1){
				vh.bm.setVisibility(View.GONE);
				vh.galery.setVisibility(View.VISIBLE);
			}else{
				vh.bm.setVisibility(View.VISIBLE);
				vh.galery.setVisibility(View.GONE);
			}
		}
	}
	private void printLeaksManager(){
		Vector<String> list = LeaksManager.getThis().checkLeaks();
		for(int i=0;i<list.size();i++){
			Log.i("MOMO_LEAKS", list.get(i));
		}
		Log.i("MOMO_LEAKS", "***************************************************************************");
	}
	class ImageLoader implements Runnable{
		private ViewHolder vh;
		private BitmapFactory.Options opt;
//		private String path;
		private Bitmap bm;
		private Bitmap sourcePhoto;
		private int position;
//		private String saveAs;
		private News item;
		private String sourcePhotoUrl;
		private String sourcePhotoPath;
		private boolean load;

		public ImageLoader(ViewHolder v,String p,String s,int pos){
			this.vh=v;
//			this.opt=opt;
//			this.path=p;
//			this.saveAs=s;
			this.position=pos;
		}

		@Override
		public void run() {
//			final long t=System.currentTimeMillis();
			try {
				load=false;
				if(vh.position==position){
					item=NewsFeedManager.INSTANCE.items.get(position);
					downloadSourceLogo();
					downloadPictures();
					//LeaksManager.getThis().monitorObject(bm);
	//				Log.i("BOOLBER", "load "+load+" "+(System.currentTimeMillis()-t));
					
				}
			} catch (FileNotFoundException e) { e.printStackTrace();
			} catch (IOException e) { e.printStackTrace(); }
		}
		private Photo[] getPhotos(){
			Photo[] photos=null;
			if(item.getAttachments()!=null){
				photos=new Photo[item.getAttachments().size()];
				for(int i=0;i<photos.length;i++){
					photos[i]=(Photo)item.getAttachments().get(i).getaFile();
				}
			}else if(item.getPhotos()!=null){
				photos=new Photo[item.getPhotos().size()];
				for(int i=0;i<photos.length;i++){
					photos[i]=(Photo)item.getPhotos().get(i);
				}
			}
			return photos;
		}
		private void downloadSourceLogo() throws MalformedURLException, IOException{
			sourcePhotoUrl=NewsFeedManager.INSTANCE.getFeedItemSourceLogo(item.getSourceId());
			sourcePhotoPath=rootFolder+"source_photo/"+item.getSourceId()+".png";
			if((new File(sourcePhotoPath).exists())){
				sourcePhoto=BitmapFactory.decodeFile(sourcePhotoPath);
			}else{
				URLConnection urlConnection = new URL(sourcePhotoUrl).openConnection();
				urlConnection.connect();
				sourcePhoto=BitmapFactory.decodeStream(urlConnection.getInputStream());
			}
			if(vh.position==position){
				vh.bm.post(new Runnable(){
					@Override
					public void run() {
						vh.logo.setImageBitmap(sourcePhoto);
						vh.text.setText(Html.fromHtml(item.getText()));
						vh.title.setText(NewsFeedManager.INSTANCE.getSourceTitle(item.getSourceId()));
						
					}
				});
			}
		}
		private void downloadPictures() throws IOException{
			final Photo[] photos=getPhotos();
			for(int i=0;i<photos.length;i++){
				String saveAs = rootFolder+""+photos[i].pid+".png";
				String path = photos[i].getBestNewsFeed();
				if((new File(saveAs).exists())){
					if(opt!=null){
						bm=BitmapFactory.decodeFile(saveAs,opt);
					}else{
						bm=BitmapFactory.decodeFile(saveAs);
					}
					load=true;
				}else{
					URL url = new URL(path);
				    URLConnection urlConnection;
				    urlConnection = url.openConnection();
					urlConnection.connect();
					bm=BitmapFactory.decodeStream(urlConnection.getInputStream());
		            File fout=new File(saveAs);
		            fout.getParentFile().mkdirs();
		            FileOutputStream fos = new FileOutputStream(fout);
		            if(bm!=null){
		            	bm.compress(CompressFormat.PNG, 100, fos);
		            }
		            
		            fos.flush();
				}
				if(vh.position==position){
					vh.bm.post(new Runnable(){
						@Override
						public void run() {
							if(photos.length==1){
								vh.bm.setScaleType(ScaleType.CENTER_CROP);
								vh.bm.setImageBitmap(bm);
							}else{
								ImageView iv=new ImageView(context);
								iv.setScaleType(ScaleType.CENTER_CROP);
								iv.setImageBitmap(bm);
								vh.gallery_root.addView(iv);
							}
							
							
						}
					});
				}
			}
		}
		
	}

}
